package sunyu.tools.mybatis;

import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.generator.DataDictionaryGenerator;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

@Component
public class DataBaseMetaBuilder {

    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getClass());

    @Resource(name = "dataSource")
    private DataSource dataSource;

    /**
     * 生成数据库字典
     *
     * @param outputPath
     * @param fileName
     */
    public void generatorDatabaseMetaData(String outputPath,
                                          String fileName) {
        logger.info("准备生成TableMeta");
        MetaBuilder metaBuilder = new MetaBuilder(dataSource);
        metaBuilder.setDialect(new MysqlDialect());
        List<TableMeta> tableMetas = metaBuilder.build();
        if (tableMetas.size() == 0) {
            logger.info("TableMeta 数量为 0，不生成任何文件");
            return;
        }

        DataDictionaryGenerator dataDictionaryGenerator = new DataDictionaryGenerator(dataSource, outputPath);
        dataDictionaryGenerator.setDataDictionaryFileName(fileName);
        dataDictionaryGenerator.generate(tableMetas);
        logger.info("TableMeta生成完毕");
    }


}
